package com.mk.admin.util;

import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class StringTool {
    /**
     * 判断是否为null或者为空
     *
     * @param str
     * @return
     */
    public static boolean isBlank(String str) {
        if (str == null || "".equals(str.trim()) || "null".equals(str) || "undefine".equals(str)) {
            return true;
        }
        return false;
    }

    /**
     * 获取随机不重复的字符串
     *
     * @param length 随机字符串的长度
     * @param str    字符内容，传空字符，则为大小写字母和数字
     * @param repeat 是否重复,true表示可以重复，false，表示不能重复
     * @return
     */
    private static String random(int length, String str, boolean repeat) {
        String chars = "";
        if (str.isEmpty()) {
            chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        } else {
            chars = str;
        }
        Random random = new Random();
        Set<Character> set = new HashSet<>();
        StringBuilder sb = new StringBuilder();
        while (sb.length() < length) {
            char randomChar = chars.charAt(random.nextInt(chars.length()));
            if (repeat) {
//                randomChar = chars.charAt(random.nextInt(chars.length()));
            } else {
                while (set.contains(randomChar)) {
                    randomChar = chars.charAt(random.nextInt(chars.length()));
                }
            }
            set.add(randomChar);
            sb.append(randomChar);
        }
        return sb.toString();
    }

    /**
     * 获取随机可重复字符串
     *
     * @param length
     * @param str
     * @return
     */
    public static String randomRepeat(int length, String str) {
        return random(length, str, true);
    }

    /**
     * 获取随机不可重复字符串
     *
     * @param length
     * @param str
     * @return
     */
    public static String randomNoRepeat(int length, String str) {
        return random(length, str, false);
    }
}
